package com.server.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.stereotype.Service;

import com.server.common.base.Message;
import com.server.service.IMsgService;

@Service("MsgService")
public class MsgService implements IMsgService {
	
	private Map<String,List<Message>> msgCache = new HashMap<>();
	
	private Lock lock = new ReentrantLock();
	
	@Override
	public void sendMsg(Message msg) {
		this.lock.lock();
		try{
			if(this.msgCache.containsKey(msg.getLoginName())){
				this.msgCache.get(msg.getLoginName()).add(msg);
			}else{
				List<Message> list = new ArrayList<>();
				list.add(msg);
				this.msgCache.put(msg.getLoginName(), list);
			}
		}finally{
			this.lock.unlock();
		}

	}
	
	@Override
	public List<List<Message>> getAllMsg(){
		List<List<Message>> content = new ArrayList<List<Message>>();
		this.lock.lock();
		try {
			if(this.msgCache.size()>0){
				System.out.println("cache > 0");
			}
			Iterator<Entry<String, List<Message>>> iterator = this.msgCache.entrySet().iterator();
			while(iterator.hasNext()){
				List<Message> value = iterator.next().getValue();
				List<Message> listDest = new ArrayList<Message>(value.size());
				for(Message msg : value){
					listDest.add(msg);
				}
				content.add(listDest);
				iterator.remove();
			}
			return content;
		} finally{
			this.lock.unlock();
		}
		
	}

	@Override
	public List<Message> getMsgs(String userId) {
		this.lock.lock();
		try{
			if(this.msgCache.containsKey(userId)){
				List<Message> list = this.msgCache.get(userId);
				if(list.size()>0){
					List<Message> listDest = new ArrayList<Message>();
					Collections.copy(listDest, this.msgCache.get(userId));
					return listDest;
				}
			}
			return null;
		}finally{
			this.lock.unlock();
		}
	}

}
